package cn.kgc.springmvc.day03.controller;

import cn.kgc.springmvc.day03.entity.ResponseResult;
import cn.kgc.springmvc.day03.entity.User;
import cn.kgc.springmvc.day03.exceptions.ParamException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2024/5/7
 * @description  登录
 */
@Controller
@RequestMapping("user")
public class UserController {


    // 登录
    @RequestMapping("login")
    @ResponseBody
    public ResponseResult  login(User user, HttpSession session){

        if("tom".equals(user.getUsername())&&"123456".equals(user.getPassword())){

            // 将用户信息存入会话对象   用于非法请求的判定
            session.setAttribute("user",user);
            return  new ResponseResult().setCode(0).setMessage("登录成功");
        }

        return  new ResponseResult().setCode(110).setMessage("用户名或密码错误");

    }


    // 删除
    @RequestMapping("delete")
    @ResponseBody
    public ResponseResult  deleteUser(Integer id) {


        if (id<0){
            throw  new ParamException("参数异常");
        }

        return  new ResponseResult().setCode(0).setMessage("数据删除成功,id="+id);
    }


    // 添加
    @RequestMapping("add")
    @ResponseBody
    public ResponseResult  addUser(User user){

        int a = 1/0;

        return  new ResponseResult().setCode(0).setMessage("数据添加成功"+user);
    }


    // springmvc 局部异常处理方案
    // @ExceptionHandler({ParamException.class})
    // @ResponseBody
    // public ResponseResult  paramExceptionHandler(ParamException e){
    //     String info = e.getInfo();
    //     return  new ResponseResult().setCode(500).setMessage(info);
    // }

    //, // @ExceptionHandler({ArithmeticException.class})
    //     // @ResponseBody
    //     // public ResponseResult  paramExceptionHandler(ArithmeticException e){
    //     //     String message = e.getMessage();
    //     //     return  new ResponseResult().setCode(500).setMessage(message);
    //     // }

}
